package com.example.teaching_server.dto;

import com.example.teaching_server.entity.UserEntity;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.time.LocalDateTime;

/**
 * 登录结果DTO
 */
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
@Schema(description = "用户登录响应结果")
public class LoginResultDTO {

    @NotNull(message = "登录状态不能为空")
    @Schema(description = "登录是否成功", example = "true", requiredMode = Schema.RequiredMode.REQUIRED)
    private Boolean success;

    @NotBlank(message = "登录消息不能为空")
    @Schema(description = "登录结果消息", example = "登录成功", requiredMode = Schema.RequiredMode.REQUIRED)
    private String message;

    @Schema(description = "JWT访问令牌", example = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...")
    private String token;

    @Schema(description = "令牌过期时间")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime tokenExpiry;

    @Schema(description = "刷新令牌")
    private String refreshToken;

    @Schema(description = "用户详细信息")
    private UserEntity user;

    /**
     * 为了兼容旧的isSuccess()调用
     */
    public boolean isSuccess() {
        return Boolean.TRUE.equals(success);
    }

    /**
     * 获取用户邮箱
     */
    @Schema(description = "用户邮箱", accessMode = Schema.AccessMode.READ_ONLY)
    public String getEmail() {
        return user != null ? user.getEmail() : null;
    }

    /**
     * 获取用户手机号
     */
    @Schema(description = "用户手机号", accessMode = Schema.AccessMode.READ_ONLY)
    public String getPhone() {
        return user != null ? user.getPhone() : null;
    }

    /**
     * 获取用户头像
     */
    @Schema(description = "用户头像URL", accessMode = Schema.AccessMode.READ_ONLY)
    public String getAvatar() {
        return user != null ? user.getAvatar() : null;
    }

    /**
     * 获取用户姓名
     */
    @Schema(description = "用户姓名", accessMode = Schema.AccessMode.READ_ONLY)
    public String getName() {
        return user != null ? user.getName() : null;
    }

    /**
     * 判断是否为教师
     */
    @Schema(description = "是否为教师角色", accessMode = Schema.AccessMode.READ_ONLY)
    public boolean isTeacher() {
        return user != null && "teacher".equals(user.getRole());
    }

    /**
     * 判断是否为学生
     */
    @Schema(description = "是否为学生角色", accessMode = Schema.AccessMode.READ_ONLY)
    public boolean isStudent() {
        return user != null && "student".equals(user.getRole());
    }

    /**
     * 判断是否为管理员
     */
    @Schema(description = "是否为管理员角色", accessMode = Schema.AccessMode.READ_ONLY)
    public boolean isAdmin() {
        return user != null && "admin".equals(user.getRole());
    }

    /**
     * 获取班级名称
     */
    @Schema(description = "所属班级名称", accessMode = Schema.AccessMode.READ_ONLY)
    public String getClassName() {
        return user != null ? user.getClassName() : null;
    }

    /**
     * 获取年级
     */
    @Schema(description = "所属年级", accessMode = Schema.AccessMode.READ_ONLY)
    public String getGrade() {
        return user != null ? user.getGradeLevel() : null;
    }

    /**
     * 获取学号
     */
    @Schema(description = "学号", accessMode = Schema.AccessMode.READ_ONLY)
    public String getStudentId() {
        return user != null ? user.getStudentId() : null;
    }

    /**
     * 获取教师ID
     */
    @Schema(description = "教师ID", accessMode = Schema.AccessMode.READ_ONLY)
    public Long getTeacherId() {
        if (user != null && user.getTeacherId() != null) {
            try {
                return Long.parseLong(user.getTeacherId());
            } catch (NumberFormatException e) {
                return null;
            }
        }
        return null;
    }

    /**
     * 获取用户角色列表
     */
    @Schema(description = "用户角色列表", accessMode = Schema.AccessMode.READ_ONLY)
    public String[] getRoles() {
        if (user == null || user.getRole() == null) {
            return new String[0];
        }
        return new String[]{user.getRole()};
    }

    /**
     * 获取用户权限列表
     */
    @Schema(description = "用户权限列表", accessMode = Schema.AccessMode.READ_ONLY)
    public String[] getPermissions() {
        // 根据角色返回相应权限
        if (isAdmin()) {
            return new String[]{"*"};
        } else if (isTeacher()) {
            return new String[]{"course:read", "course:write", "student:read"};
        } else if (isStudent()) {
            return new String[]{"course:read", "homework:read", "homework:write"};
        }
        return new String[]{};
    }

    /**
     * 成功登录响应
     */
    public static LoginResultDTO success(String token, UserEntity user, String message) {
        return LoginResultDTO.builder()
                .success(true)
                .message(message != null ? message : "登录成功")
                .token(token)
                .tokenExpiry(LocalDateTime.now().plusHours(2)) // 默认2小时过期
                .user(user)
                .build();
    }

    /**
     * 失败登录响应
     */
    public static LoginResultDTO fail(String message) {
        return LoginResultDTO.builder()
                .success(false)
                .message(message)
                .build();
    }

    /**
     * 验证令牌是否有效
     */
    @Schema(description = "令牌是否有效", accessMode = Schema.AccessMode.READ_ONLY)
    public boolean isTokenValid() {
        return token != null && !token.trim().isEmpty() &&
                (tokenExpiry == null || tokenExpiry.isAfter(LocalDateTime.now()));
    }
}
